# -*- coding: utf-8 -*-

"""
公告管理函数
"""
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
import pandas as pd
import uuid
import datetime
import re
import hashlib
from ...pao_python.pao.service.security.security_service import RoleService
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...service.common import (insert_data, find_data, update_data, delete_data,
                               get_condition, get_info, get_current_user_id, operation_result)
from ...service.buss_pub.bill_manage import (
    BillManageService, OperationType, TypeId, Status)
from server.pao_python.pao.service.data.mongo_db import (
    MongoService, MongoFilter, C, N, F, as_date)
from ...service.mongo_bill_service import MongoBillFilter


class AnnouncementService(MongoService):
    """ 公告管理 """

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.role_service = RoleService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session
        )
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session
        )

    def get_announcement_list(self, order_ids, condition, page, count):
        """获取公告列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        """
        if 'date_range' in list(condition.keys()):
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
        keys = ["id", 'title', 'promulgator',
                'start_date', 'end_date', 'showing_status']
        values = self.get_value(condition, keys)
        print('1111', condition)
        _filter_type = MongoBillFilter()
        _filter_type.match_bill((C('organization_id').inner(order_ids)) & (C("name").like('公告')) | (C("name").like('announcement'))).project(
            {"_id": 0})
        res_type = self.query(_filter_type, "PT_Article_Type")
        _filter = MongoBillFilter()
        _filter.lookup_bill("PT_User", "promulgator_id", "id", "promulgator")\
            .add_fields({"promulgator": "$promulgator.name"})\
            .match_bill((C("promulgator").like(values['promulgator']))
                        & (C('title').like(values['title']))
                        & (C("id") == values["id"])
                        & (C("showing_status") == values["showing_status"])
                        & (C('create_date') >= as_date(values['start_date']))
                        & (C('create_date') <= as_date(values['end_date'])))\
            .project({"_id": 0, "promulgator._id": 0})
        if res_type:
            _filter.match_bill((C('type_id') == res_type[0].get('id')))
        res = self.page_query(_filter, "PT_Article", page, count)
        return res

    def update_announcement(self, announcement):
        """# 新增公告"""
        res = "Fail"
        # 无论编辑还是新增，状态都是待审核
        announcement["status"] = "auditing"
        announcement["issue_date"] = (
            as_date(announcement.get("issue_date"))
            if announcement.get("issue_date")
            else datetime.datetime.now()
        )
        _filter = MongoFilter()
        _filter.match((C("bill_status") == "valid") & ((C("name") == '公告') | (C("name") == 'announcement'))).project(
            {"_id": 0})
        res_announcement = self.query(_filter, "PT_Article_Type")
        announcement['type_id'] = res_announcement[0].get(
            'id') if res_announcement else ''
        person_id = get_current_user_id(self.session)
        announcement["promulgator_id"] = person_id
        # 判断新增/编辑
        flag = OperationType.update.value if announcement.get(
            'id') else OperationType.add.value
        bill_id = self.bill_manage_service.add_bill(
            flag,
            TypeId.announcement.value,
            announcement,
            "PT_Article",
        )

        return operation_result(bill_id)

    def delete_announcement(self, announcement_ids):
        """删除公告

        Arguments:
            announcement_ids   {ids}      数据id
        """
        res = "fail"

        def process_func(db):
            nonlocal res
            ids = []
            if isinstance(announcement_ids, str):
                ids.append(announcement_ids)
            else:
                ids = announcement_ids
            for announcement_id in ids:
                # 查询被删除的数据信息
                data = find_data(
                    db,
                    "PT_Article",
                    {"id": announcement_id, "bill_status": Status.bill_valid.value},
                )
                if len(data) > 0:
                    self.bill_manage_service.add_bill(
                        OperationType.delete.value,
                        TypeId.announcement.value,
                        data[0],
                        "PT_Article",
                    )
            res = "Success"

        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res
